<template>
	<div id="space-manage-view">
		<!-- 标题栏 -->
		<a-flex justify="space-between" align="center" style="margin-bottom: 16px">
			<h2>空间成员管理</h2>
			<a-space>
				<a-button type="primary" href="/add_space" target="_blank">+ 创建空间</a-button>
				<a-button type="primary" ghost href="/space_analyze?queryPublic=1" target="_blank">分析公共图库</a-button>
				<a-button type="primary" ghost href="/space_analyze?queryAll=1" target="_blank">分析全部空间</a-button>
			</a-space>
		</a-flex>
		<!-- 添加成员表单 -->
		<a-form layout="inline" :model="formData" @finish="handleSubmit">
			<a-form-item label="用户 id" name="userId">
				<a-input v-model:value="formData.userId" placeholder="请输入用户 id" allow-clear />
			</a-form-item>
			<a-form-item>
				<a-button type="primary" html-type="submit">添加用户</a-button>
			</a-form-item>
		</a-form>

		<div style="margin-bottom: 16px"></div>

		<!-- 表格 -->
		<a-table :columns="columns" :data-source="dataList">
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'userInfo'">
					<a-space>
						<a-avatar :src="record.user?.userAvatar" />
						{{ record.user?.userName }}
					</a-space>
				</template>
				<template v-if="column.dataIndex === 'spaceRole'">
					<a-select
						v-model:value="record.spaceRole"
						:options="SPACE_ROLE_OPTIONS"
						@change="(value) => editSpaceRole(value, record)"
					/>
				</template>
				<template v-else-if="column.dataIndex === 'createTime'">
					{{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
				</template>
				<template v-else-if="column.dataIndex === 'action'">
					<a-space wrap>
						<a-button type="link" danger @click="doDelete(record.id)">删除</a-button>
					</a-space>
				</template>
			</template>
		</a-table>
	</div>
</template>

<script lang="ts" setup>
import { message, Modal } from 'ant-design-vue'
import { onMounted, reactive, ref } from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'
import dayjs from 'dayjs'
import { SPACE_LEVEL_OPTIONS, SPACE_ROLE_OPTIONS } from '@/constants/space'
import {
	addSpaceUserUsingPost,
	deleteSpaceUserUsingPost,
	editSpaceUserUsingPost,
	listSpaceUserUsingPost,
} from '@/api/spaceUserController'

interface Props {
	id: string
}

const props = defineProps<Props>()

// 添加成员表单
const formData = reactive<API.SpaceUserAddRequest>({})

// 表单列
const columns = [
	{ title: '用户', dataIndex: 'userInfo', align: 'left' },
	{ title: '角色', dataIndex: 'spaceRole', align: 'left' },
	{ title: '创建时间', dataIndex: 'createTime', align: 'left' },
	{ title: '操作', dataIndex: 'action', align: 'center' },
]

const handleSubmit = async () => {
	const spaceId: any = props.id
	if (!spaceId) {
		return
	}
	const res = await addSpaceUserUsingPost({
		spaceId,
		...formData,
	})
	if (res.data.code === 0) {
		message.success('添加成功')
		// 刷新数据
		fetchData()
	} else {
		message.error('添加失败，' + res.data.message)
	}
}

// 表单数据
const dataList = ref<API.SpaceUserVO[]>([])

// 获取数据
const fetchData = async () => {
	const spaceId: any = props.id
	if (!spaceId) {
		return
	}
	const res = await listSpaceUserUsingPost({
		spaceId,
	})
	if (res.data.code === 0 && res.data.data) {
		dataList.value = res.data.data ?? []
	} else {
		message.error('获取数据失败：' + res.data.message)
	}
}

// 删除操作
const doDelete = async (id: number) => {
	if (!id) {
		return
	}

	Modal.confirm({
		title: '⚠️ 危险操作确认',
		icon: createVNode(ExclamationCircleOutlined),
		content: `确定要删除这个空间吗？此操作不可恢复，请谨慎操作！\n\n空间ID: ${id}`,
		okText: '确认删除',
		okType: 'danger',
		cancelText: '取消',
		width: 400,
		async onOk() {
			try {
				const res = await deleteSpaceUserUsingPost({ id })
				if (res.data.code === 0) {
					message.success('删除成功')
					// 删除成功后重新获取数据
					await fetchData()
				} else {
					message.error('删除失败：' + res.data.message)
				}
			} catch {
				message.error('删除失败，请重试')
			}
		},
	})
}

// 编辑成员角色
const editSpaceRole = async (value, record) => {
	const res = await editSpaceUserUsingPost({
		id: record.id,
		spaceRole: value,
	})
	if (res.data.code === 0) {
		message.success('修改成功')
	} else {
		message.error('修改失败，' + res.data.message)
	}
}

// 页面加载时获取数据，请求一次
onMounted(() => {
	// 初始化搜索参数
	fetchData()
})
</script>

<style scoped lang="scss"></style>
